package edu.iscas.appcheckclient.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import edu.iscas.appcheckclient.R;
import edu.iscas.appcheckclient.model.TestApp;
import edu.iscas.appcheckclient.service.FloatingWindowService;
import edu.iscas.appcheckclient.util.ShellUtils;

public class TestListActivity extends AppCompatActivity {

    private List<TestApp> testList;

    private static final String TAG = TestListActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        testList = getPmListInstrumentation();

        ListView testListView = (ListView)findViewById(R.id.test_list_view);
        testListView.setAdapter(new ArrayAdapter<TestApp>(this,
                android.R.layout.simple_list_item_1, testList));
        testListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TestApp testApp = (TestApp) parent.getAdapter().getItem(position);
                //startTestApp(testApp);
                Intent intent = new Intent(TestListActivity.this, FloatingWindowService.class);
                intent.putExtra(getResources().getString(R.string.key_test_name), testApp.getName());
                startService(intent);
            }
        });

//
//        try {
//            File file = new File("/data/data/com.example.android.apis/files", "record");
//            if(file == null){
//                Log.e(tag, "file not found");
//            }else {
//                FileInputStream inputStream = new FileInputStream(file);
//                InputStreamReader reader = new InputStreamReader(inputStream);
//                BufferedReader br = new BufferedReader(reader);
//                String line = "";
//                while ((line = br.readLine()) != null) {
//                    Log.i(tag, line);
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    public static void startTestApp(TestApp testApp){
        Log.i(TAG, "about to exec shell command : " + "am instrument " + testApp.toString());
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand("am instrument " + testApp.toString(), true, true);
        if (commandResult.result == 0){
            if(commandResult.successMsg != null) {
                Log.i(TAG, commandResult.successMsg);
            }
        }else{
            if(commandResult.errorMsg != null) {
                Log.e(TAG, commandResult.errorMsg);
            }
        }

    }

    public static void startTestApp(String testApp){
        Log.i(TAG, "about to exec shell command : " + "am instrument " + testApp.toString());
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand("am instrument " + testApp.toString(), true, true);
        if (commandResult.result == 0){
            if(commandResult.successMsg != null) {
                Log.i(TAG, commandResult.successMsg);
            }
        }else{
            if(commandResult.errorMsg != null) {
                Log.e(TAG, commandResult.errorMsg);
            }
        }
    }

    public static List<TestApp> getPmListInstrumentation(){
        List<TestApp> resultList = new ArrayList<TestApp>();
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand("pm list instrumentation", false, true);
        if (commandResult.result == 0 && commandResult.successMsg != null && commandResult.successMsg.length() > 0){
            String[] instrumentationList = commandResult.successMsg.split("instrumentation:");
            for(String str : instrumentationList){
                if(str.equals("") || str == null) {
                    continue;
                }
                str = str.substring(0, str.indexOf(" "));
                TestApp testApp = new TestApp(str);
                resultList.add(testApp);
                //Log.i(tag, str);
            }
            return resultList;
        }else{
            Log.e(TAG, commandResult.errorMsg);
            return resultList;
        }
    }
}
